package com.med.config;
import com.med.service.IAppointmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * 预约超时监听器（监听Redis键过期事件）
 * 若依微服务中需放在listener包下，确保被@ComponentScan扫描
 */
@Component
@Slf4j
public class AppointmentExpireListener extends KeyExpirationEventMessageListener {

    @Autowired
    private IAppointmentService appointmentService;

    // 注入Redis消息监听容器（若依配置中已定义）
    public AppointmentExpireListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 当Redis键过期时触发（处理预约超时）
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = message.toString();
        log.info("监听到Redis键过期：{}", expiredKey);

        // 只处理预约超时的键（格式：appointment:expire:{appointmentId}）
        if (expiredKey.startsWith("appointment:expire:")) {
            try {
                // 提取预约ID（如从"appointment:expire:100"中获取100）
                String appointmentIdStr = expiredKey.replace("appointment:expire:", "");
                Integer appointmentId = Integer.parseInt(appointmentIdStr);
                // 调用服务层处理超时预约
                appointmentService.handleExpiredAppointment(appointmentId);
                log.info("处理超时预约成功，appointmentId：{}", appointmentId);
            } catch (NumberFormatException e) {
                log.error("预约ID格式错误，键：{}", expiredKey, e);
            } catch (Exception e) {
                log.error("处理超时预约失败，键：{}", expiredKey, e);
            }
        }
    }
}